﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AdvanceLib.ScriptCore;

namespace AdvanceLib.Extension.XseScript
{
    public class ScriptCommand : ICommand
    {
        #region Constructors
        public ScriptCommand(XseExtensionProvider provider)
        {
            this._provider = provider;
            this.Parameters = new List<ScriptParam>();
        }
        #endregion

        #region Fields
        private XseExtensionProvider _provider;
        #endregion

        #region Properties
        public string Name { get; set; }
        public byte HexCode { get; set; }
        public List<ScriptParam> Parameters { get; set; }
        #endregion

        #region Methods
        private byte[] IntToByteArray(int value)
        {
            byte[] bytes = new byte[4];

            bytes[0] = (byte)(value >> 24);
            bytes[1] = (byte)(value >> 16);
            bytes[2] = (byte)(value >> 8);
            bytes[3] = (byte)value;

            return bytes;
        }
        #endregion

        #region ICommand Member
        public byte[] GetHexCode()
        {
            int currentIndex = 0;
            byte[] hexCode = new byte[this.GetLength()];

            hexCode[currentIndex++] = this.HexCode;

            for (int i = 0; i < this.Parameters.Count; i++)
            {
                List<byte> parameterList = new List<byte>();

                for (int j = 0; j < this.Parameters[i].Length; j++)
                {
                    if (this.Parameters[i].IsDynamic)
                    {
                        long offset = 0x08000000 + this._provider.Host.GetOffset(this.Parameters[i].DynamicName);

                        this.Parameters[i].DynamicName = string.Empty;
                        this.Parameters[i].Value = this.IntToByteArray((int)offset);
                    }
                    parameterList.Add(this.Parameters[i].Value[j]);
                }

                byte[] inverted = parameterList.Reverse<byte>().ToArray();
                for (int k = 0; k < inverted.Length; k++)
                {
                    hexCode[currentIndex++] = inverted[k];
                }
            }

            return hexCode;
        }
        public int GetLength()
        {
            int length = 1; //Command [1 Byte]
            for (int i = 0; i < this.Parameters.Count; i++)
            {
                length += this.Parameters[i].Length;
            }
            return length;
        }
        #endregion
    }
}
